<?php
/**
 * st
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 采用最新Thinkphp5助手函数特性实现单字母函数M D U等简写方式
 * ============================================================================
 * Author: 当燃
 * Date: 2015-09-09
 */

namespace app\admin\controller;
use app\admin\logic\GoodsLogic;
use app\admin\logic\OrderLogic;
use think\AjaxPage;
use think\console\command\make\Model;
use think\Page;
use think\Verify;
use think\Db;
use app\admin\logic\UsersLogic;
use app\common\model\Withdrawals;
use app\common\model\Users;
use think\Loader;

class Distribut extends Base {

    public function index(){

        $parentid = session('user_id');
        $this->assign('parentid',$parentid);
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        $this->assign('province',$province);
        return $this->fetch();
    }

    /**
     * 城市合伙人列表
     */
    public function ajaxindex(){
        $condition = array();
        $nickname = I('nickname');
        $account = I('account');
        $province = I('province');
        $city = I('city');
        $district = I('district');
        $parentid = session('user_id');
        if($parentid){
            $condition['parent_id'] = $parentid;
        }
        $account ? $condition['email|mobile'] = ['like',"%$account%"] : false;
        $nickname ? $condition['nickname'] = ['like',"%$nickname%"] : false;
        $province ? $condition['province'] = $province : false;
        $city ? $condition['city'] = $city : false;
        $district ? $condition['district'] = $district : false;
        $condition['distribut_level'] = ['lt',"3"];
        I('first_leader') && ($condition['first_leader'] = I('first_leader')); // 查看一级下线人有哪些
        I('second_leader') && ($condition['second_leader'] = I('second_leader')); // 查看二级下线人有哪些
        I('third_leader') && ($condition['third_leader'] = I('third_leader')); // 查看三级下线人有哪些
        $sort_order = I('order_by').' '.I('sort');

        $usersModel = new Users();
        $count = $usersModel->where($condition)->whereOr('user_id',$parentid)->count();
        $Page  = new AjaxPage($count,10);
        $userList = $usersModel->where($condition)->whereOr('user_id',$parentid)->order($sort_order)->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach ($userList as $key=>&$item) {
            $item['pinfo'] = M('users')->find($item['parent_id']);
            $item['distribut_level']==2?$item['distribut_name']='城市合伙人':$item['distribut_name']='省级合伙人';
        }
        $show = $Page->show();
        $this->assign('userList',$userList);
        $this->assign('level',M('user_level')->getField('level_id,level_name'));
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }
    public function search_user()
    {
        $search_key = trim(I('search_key'));
        if ($search_key == '') $this->ajaxReturn(['status'=>-1,'msg'=>'请按要求输入！！']);
        $list = M('users')->where(['nickname'=>['like',"%$search_key%"],'distribut_level'=>['lt',"3"]])->select();

        if ($list){
            $this->ajaxReturn(['status'=>1,'msg'=>'获取成功','result'=>$list]);
        }
        $this->ajaxReturn(['status'=>-1,'msg'=>'未查询到相应数据！！']);
    }
    /**
     * 城市合伙人详细信息查看
     */
    public function detail(){
        $uid = I('get.id');
        $user = D('users')->where(array('user_id'=>$uid))->find();
        $user['distribut_level']==2?$user['distribut_name']='城市合伙人':$user['distribut_name']='省级合伙人';
        if(!$user)
            exit($this->error('会员不存在'));
        if(IS_POST){
            //  会员信息编辑
            $password = I('post.password');
            $password2 = I('post.password2');
            if($password != '' && $password != $password2){
                exit($this->error('两次输入密码不同'));
            }
            if($password == '' && $password2 == ''){
                unset($_POST['password']);
            }else{
                $_POST['password'] = encrypt($_POST['password']);
            }

            if(!empty($_POST['mobile']))
            {   $mobile = trim($_POST['mobile']);
                $c = M('users')->where("user_id != $uid and mobile = '$mobile'")->count();
                $c && exit($this->error('手机号不得和已有用户重复'));
            }

            $row = M('users')->where(array('user_id'=>$uid))->save($_POST);
            $user_obj = new UsersLogic();
            if($row){
                $user_obj->accountedit($uid);
                exit($this->success('修改成功'));
            }else{
                exit($this->error('未作内容修改或修改失败'));
            }

        }

        $this->assign('user',$user);
        return $this->fetch();
    }
    public function sqtixian(){
        $uid = I('get.id');
        $user = D('users')->where(array('user_id'=>$uid))->find();
        if(!$user)
            exit($this->error('会员不存在'));
        if($user['user_money']==0){
            exit($this->error('暂无提现金额'));
        }
        if(IS_POST){
            //  会员信息编辑
            $id = $this->request->param('id');
            $userres = Db::name('users')->find($id);
            $money = $this->request->param('money');
            $res = Db::name('user_txrecord')->where('uid',$id)->where('type',0)->select();
            if($res){
                exit($this->error('无法提现,已有一笔提现申请在审核中'));
            }else{
                $record['uid'] = $id;
                $record['nickname'] = $userres['nickname'];
                $record['type'] = 0;
                $record['record'] = '申请提现'.$money.'元';
                $record['money'] = $money;
                $record['add_time'] = time();
                $res = Db::name('user_txrecord')->insertGetId($record);
                if($res){
                    $this->success('申请成功',U('Distribut/index'));exit;
                }else{
                    exit($this->error('提现申请失败'));
                }

            }

        }

        $this->assign('user',$user);
        return $this->fetch();
    }
    public function add_user(){
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        $this->assign('province',$province);
        $GoodsLogic = new GoodsLogic();
        $all_member = M('users')->where("distribut_level<3")->getField('user_id,nickname,parent_id,province,city');//上级分类数据集，限制3级分类，那么只拿前两级作为上级选择
        if(!empty($all_member)){
            $cat_select = $GoodsLogic->exportUserTree($all_member,0,0);
            $this->assign('cat_select',$cat_select);
        }

        if(IS_POST){
            $data = I('post.');
            $user_obj = new UsersLogic();
            $data['distribut_level'] = 2;
            $res = $user_obj->addUser($data);
            $parentid = I('parent_id');
            if($res['status'] == 1){
                if($parentid){
                    $user_obj->checkPuser($parentid,2,$data['nickname']);
                }
                //分配后台账号
                    $user_obj->accountAdd($res['user_id']);

                $this->success('添加成功',U('Distribut/index'));exit;
            }else{
                $this->error('添加失败,'.$res['msg'],U('Distribut/index'));
            }
        }
        return $this->fetch();
    }
    public function mzindex(){
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        $this->assign('province',$province);
        return $this->fetch();
    }
    /**
     *,门诊列表
     */
    public function ajaxmzindex(){
        // 搜索条件
        $condition = array();
        $nickname = I('nickname');
        $account = I('account');
        $province = I('province');
        $city = I('city');
        $district = I('district');
        $account ? $condition['email|mobile'] = ['like',"%$account%"] : false;
        $nickname ? $condition['nickname'] = ['like',"%$nickname%"] : false;
        $province ? $condition['province'] = $province : false;
        $city ? $condition['city'] = $city : false;
        $district ? $condition['district'] = $district : false;
        $parentid = session('user_id');
        if($parentid){
            $condition['parent_id'] = $parentid;
            $adminres = Db::name('users')->find($parentid);
            if($adminres['distribut_level']==1){
                $fields = Db::name('users')->where('parent_id',$parentid)->column('user_id');
                $userIds = implode(",",$fields);
                $condition['parent_id'] = array('in',$userIds.','.$parentid);
            }
        }
        $condition['distribut_level'] = 3;
//        I('first_leader') && ($condition['first_leader'] = I('first_leader')); // 查看一级下线人有哪些
//        I('second_leader') && ($condition['second_leader'] = I('second_leader')); // 查看二级下线人有哪些
//        I('third_leader') && ($condition['third_leader'] = I('third_leader')); // 查看三级下线人有哪些
        $sort_order = I('order_by').' '.I('sort');
        $regionList = get_region_list();
        $usersModel = new Users();
        $count = $usersModel->where($condition)->count();
        $Page  = new AjaxPage($count,10);
        $userList = $usersModel->where($condition)->order($sort_order)->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach ($userList as $key=>&$item) {
            $item['pinfo'] = M('users')->find($item['parent_id']);
            $item['distribut_name']='门诊';
            $item['alladdress']= "{$regionList[$item['province']]},{$regionList[$item['city']]},{$regionList[$item['district']]},{$item['address']}";
        }
        $show = $Page->show();
        $this->assign('userList',$userList);
        $this->assign('level',M('user_level')->getField('level_id,level_name'));
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }
    public function add_mzuser(){
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        $this->assign('province',$province);
        $GoodsLogic = new GoodsLogic();
        $all_member = M('users')->where("distribut_level<3")->getField('user_id,nickname,parent_id,province,city');//上级分类数据集，限制3级分类，那么只拿前两级作为上级选择
        if(!empty($all_member)){
            $cat_select = $GoodsLogic->exportUserTree($all_member,0,0);
            $this->assign('cat_select',$cat_select);
        }

        if(IS_POST){
            $data = I('post.');
            $user_obj = new UsersLogic();
            $data['distribut_level'] = 3;
            $res = $user_obj->addUser($data);
            $parentid = I('parent_id');
            if($res['status'] == 1){
                if($parentid){
                    $user_obj->checkPuser($parentid,3,$data['nickname']);
                }
                $this->success('添加成功',U('Distribut/mzindex'));exit;
            }else{
                $this->error('添加失败,'.$res['msg'],U('Distribut/mzindex'));
            }
        }
        return $this->fetch();
    }


    /**
     * 门诊详细信息查看
     */
    public function mzdetail(){
        $uid = I('get.id');
        $user = D('users')->where(array('user_id'=>$uid))->find();
        $user['distribut_level']=='门诊';
        $city_list = Db::name('region')->where(['parent_id'=>$user['province'],'level'=> 2])->select();
        $district_list = Db::name('region')->where(['parent_id'=>$user['city']])->select();
        $this->assign('city', $city_list);
        $this->assign('area', $district_list);
        $province_list = Db::name('region')->where(['parent_id'=>0,'level'=> 1])->cache(true)->select();
        $this->assign('province', $province_list);
        $all_member = M('users')->where("distribut_level<3")->getField('user_id,nickname,parent_id,province,city');//上级分类数据集，限制3级分类，那么只拿前两级作为上级选择
       
            $this->assign('all_member',$all_member);
       
        if(!$user)
            exit($this->error('会员不存在'));
        if(IS_POST){
            //  会员信息编辑
            $password = I('post.password');
            $password2 = I('post.password2');
            if($password != '' && $password != $password2){
                exit($this->error('两次输入密码不同'));
            }
            if($password == '' && $password2 == ''){
                unset($_POST['password']);
            }else{
                $_POST['password'] = encrypt($_POST['password']);
            }
			if($user['parent_id']==0 && $_POST['parent_id']!=0){
               $row = M('users')->where(array('user_id'=>$_POST['parent_id']))->setInc('next_mznum',1);
            }

            if(!empty($_POST['mobile']))
            {   $mobile = trim($_POST['mobile']);
                $c = M('users')->where("user_id != $uid and mobile = '$mobile'")->count();
                $c && exit($this->error('手机号不得和已有用户重复'));
            }

            $row = M('users')->where(array('user_id'=>$uid))->save($_POST);
            if($row)
                exit($this->success('修改成功'));
            exit($this->error('未作内容修改或修改失败'));
        }

        $this->assign('user',$user);
        return $this->fetch();
    }
    public function export_cityuser(){
        $strTable ='<table width="700" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">会员ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">会员昵称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">会员等级</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">省、市</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">手机号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">注册时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">推荐合伙人数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">推荐奖金</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">下级门诊数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">下级门诊推荐奖金</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">下级门诊订单收益</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">二级门诊数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">二级门诊推荐奖金</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">二级门诊订单收益</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">总金额</td>';
        $strTable .= '</tr>';
        $user_ids =I('user_ids');
        $condition['distribut_level'] = array("lt",'3');
        if($user_ids){
            $condition['user_id']=['in',$user_ids];
        }else{
            $mobile =I('mobile');
            $email =I('email');
            $mobile ? $condition['mobile'] = $mobile : false;
            $email ? $condition['email'] = $email : false;
        };
        $count = DB::name('users')->where($condition)->count();
        $p = ceil($count/5000);
        $regionList = get_region_list();
        for($i=0;$i<$p;$i++){
            $start = $i*5000;
            $end = ($i+1)*5000;
            $userList = M('users')->where($condition)->order('user_id')->limit($start.','.$end)->select();

            if(is_array($userList)){
                foreach($userList as $k=>$val){
                    $val['distribut_level']==2?$val['distribut_name']='城市合伙人':$val['distribut_name']='省级合伙人';
                    $strTable .= '<tr>';
                    $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['user_id'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['nickname'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['distribut_name'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'."{$regionList[$val['province']]},{$regionList[$val['city']]}".'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i',$val['reg_time']).'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['friend_num'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['friend_money'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['next_mznum'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['next_mzmoney'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['next_ordermoney'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['second_mznum'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['second_mzmoney'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['second_ordermoney'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['total_amount'].' </td>';
                    $strTable .= '</tr>';
                }
                unset($userList);
            }
        }
        $strTable .='</table>';
        downloadExcel($strTable,'users_'.$i);
        exit();
    }
    public function export_mzuser(){
        $strTable ='<table width="700" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">会员ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">会员昵称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">会员等级</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">省、市</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">手机号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">上级</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">上级号码</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">注册时间</td>';
        $strTable .= '</tr>';
        $user_ids =I('user_ids');
        $condition['distribut_level'] = '3';
        if($user_ids){
            $condition['user_id']=['in',$user_ids];
        }else{
            $mobile =I('mobile');
            $email =I('email');
            $mobile ? $condition['mobile'] = $mobile : false;
            $email ? $condition['email'] = $email : false;
        };
        $count = DB::name('users')->where($condition)->count();
        $p = ceil($count/5000);
        $regionList = get_region_list();
        for($i=0;$i<$p;$i++){
            $start = $i*5000;
            $end = ($i+1)*5000;
            $userList = M('users')->where($condition)->order('user_id')->limit($start.','.$end)->select();

            if(is_array($userList)){
                foreach($userList as $k=>$val){
                    $pinfo = M('users')->find($val['parent_id']);
                    $val['distribut_level']==3?$val['distribut_name']='门诊':$val['distribut_name']='无';
                    $strTable .= '<tr>';
                    $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['user_id'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['nickname'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['distribut_name'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'."{$regionList[$val['province']]},{$regionList[$val['city']]}".'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$pinfo['nickname'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$pinfo['mobile'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i',$val['reg_time']).'</td>';
                    $strTable .= '</tr>';
                }
                unset($userList);
            }
        }
        $strTable .='</table>';
        downloadExcel($strTable,'users_'.$i);
        exit();
    }
    public function treeindex(){
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        $this->assign('province',$province);
        return $this->fetch();
    }
    public function ajaxtreeindex(){
        $condition = array();
        $nickname = I('nickname');
        $account = I('account');
        $province = I('province');
        $city = I('city');
        $district = I('district');
        $account ? $condition['email|mobile'] = ['like',"%$account%"] : false;
        $nickname ? $condition['nickname'] = ['like',"%$nickname%"] : false;
        $province ? $condition['province'] = $province : false;
        $city ? $condition['city'] = $city : false;
        $district ? $condition['district'] = $district : false;
        $usersModel = new Users();
        $parentid = session('user_id');
        if($parentid){
            $adminres = Db::name('users')->find($parentid);
            if($adminres['distribut_level']==1){
                $fields = Db::name('users')->where('parent_id',$parentid)->column('user_id');
                $userIds = $parentid.",".implode(",",$fields);
                $condition['parent_id'] = array('in',$userIds);
            }
            $count = $usersModel->where($condition)->count();

            $userList = Db::name('users')->where($condition)->whereOr('user_id',$parentid)->select();
        }else{
            $count = $usersModel->where($condition)->count();

            $userList = Db::name('users')->where($condition)->select();
        }


        $arr = array(
            "1"=>'省级合伙人',
            "2"=>'城市合伙人',
            "3"=>'门诊'
        );
        foreach ($userList as $key=>&$item) {
            $item['pinfo'] = M('users')->find($item['parent_id']);
            $item['distribut_name']=$arr[$item['distribut_level']];
        }
        $data = arr2table($userList);
        $this->assign('userList',$data);
        $this->assign('count',$count);
        return $this->fetch();
    }
    /**
     * 用户收货地址查看
     */
    public function address(){
        $uid = I('get.id');
        $lists = D('user_address')->where(array('user_id'=>$uid))->select();
        $regionList = get_region_list();
        $this->assign('regionList',$regionList);
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    /**
     * 删除会员
     */
    public function delete(){
        $uid = I('get.id');

        //先删除ouath_users表的关联数据
        M('OuathUsers')->where(array('user_id'=>$uid))->delete();
        $row = M('users')->where(array('user_id'=>$uid))->delete();
        if($row){
            $this->success('成功删除会员');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 删除会员
     */
    public function ajax_delete(){
        $uid = I('id');
        if($uid){
            $row = M('users')->where(array('user_id'=>$uid))->delete();
            if($row !== false){
                //把关联的第三方账号删除
                M('OauthUsers')->where(array('user_id'=>$uid))->delete();
                $this->ajaxReturn(array('status' => 1, 'msg' => '删除成功', 'data' => ''));
            }else{
                $this->ajaxReturn(array('status' => 0, 'msg' => '删除失败', 'data' => ''));
            }
        }else{
            $this->ajaxReturn(array('status' => 0, 'msg' => '参数错误', 'data' => ''));
        }
    }

    /**
     * 账户资金记录
     */
    public function account_log(){
        $user_id = I('get.id');
        //获取类型
        $type = I('get.type');
        //获取记录总数
        $count = M('account_log')->where(array('user_id'=>$user_id))->count();
        $page = new Page($count);
        $lists  = M('account_log')->where(array('user_id'=>$user_id))->order('change_time desc')->limit($page->firstRow.','.$page->listRows)->select();

        $this->assign('user_id',$user_id);
        $this->assign('page',$page->show());
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    /**
     * 账户资金调节
     */
    public function account_edit(){
        $user_id = I('user_id');
        if(!$user_id > 0) $this->ajaxReturn(['status'=>0,'msg'=>"参数有误"]);
        $user = M('users')->field('user_id,user_money,frozen_money,pay_points,is_lock')->where('user_id',$user_id)->find();
        if(IS_POST){
            $desc = I('post.desc');
            if(!$desc)
                $this->ajaxReturn(['status'=>0,'msg'=>"请填写操作说明"]);
            //加减用户资金
            $m_op_type = I('post.money_act_type');
            $user_money = I('post.user_money/f');
            $user_money =  $m_op_type ? $user_money : 0-$user_money;
            if (($user['user_money']+$user_money)<0){
                $this->ajaxReturn(['status'=>0,'msg'=>"用户剩余资金不足！！"]);
            }
            //加减用户积分
            $p_op_type = I('post.point_act_type');
            $pay_points = I('post.pay_points/d');
            $pay_points =  $p_op_type ? $pay_points : 0-$pay_points;
            if(($pay_points+$user['pay_points'])<0 ){
                $this->ajaxReturn(['status'=>0,'msg'=>'用户剩余积分不足！！']);
            }
            //加减冻结资金
            $f_op_type = I('post.frozen_act_type');
            $revision_frozen_money = I('post.frozen_money/f');
            if( $revision_frozen_money != 0){    //有加减冻结资金的时候
                $frozen_money =  $f_op_type ? $revision_frozen_money : 0-$revision_frozen_money;
                $frozen_money = $user['frozen_money']+$frozen_money;    //计算用户被冻结的资金
                if($f_op_type==1 && $revision_frozen_money > $user['user_money'])
                {
                    $this->ajaxReturn(['status'=>0,'msg'=>"用户剩余资金不足！！"]);
                }
                if($f_op_type==0 && $revision_frozen_money > $user['frozen_money'])
                {
                    $this->ajaxReturn(['status'=>0,'msg'=>"冻结的资金不足！！"]);
                }
                $user_money = $f_op_type ? 0-$revision_frozen_money : $revision_frozen_money ;    //计算用户剩余资金
                M('users')->where('user_id',$user_id)->update(['frozen_money' => $frozen_money]);
            }
            if(accountLog($user_id,$user_money,$pay_points,$desc,0))
            {
                $this->ajaxReturn(['status'=>1,'msg'=>"操作成功",'url'=>U("Admin/User/account_log",array('id'=>$user_id))]);
            }else{
                $this->ajaxReturn(['status'=>-1,'msg'=>"操作失败"]);
            }
            exit;
        }
        $this->assign('user_id',$user_id);
        $this->assign('user',$user);
        return $this->fetch();
    }

    public function recharge(){
        $timegap = urldecode(I('timegap'));
        $nickname = I('nickname');
        $map = array();
        if($timegap){
            $gap = explode(',', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
            $map['ctime'] = array('between',array(strtotime($begin),strtotime($end)));
            $this->assign('begin',$begin);
            $this->assign('end',$end);
        }
        if($nickname){
            $map['nickname'] = array('like',"%$nickname%");
            $this->assign('nickname',$nickname);
        }
        $count = M('recharge')->where($map)->count();
        $page = new Page($count);
        $lists  = M('recharge')->where($map)->order('ctime desc')->limit($page->firstRow.','.$page->listRows)->select();
        $this->assign('page',$page->show());
        $this->assign('pager',$page);
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    public function level(){
        $act = I('get.act','add');
        $this->assign('act',$act);
        $level_id = I('get.level_id');
        if($level_id){
            $level_info = D('user_level')->where('level_id='.$level_id)->find();
            $this->assign('info',$level_info);
        }
        return $this->fetch();
    }

    public function levelList(){
        $Ad =  M('user_level');
        $p = $this->request->param('p');
        $res = $Ad->order('level_id')->page($p.',10')->select();
        if($res){
            foreach ($res as $val){
                $list[] = $val;
            }
        }
        $this->assign('list',$list);
        $count = $Ad->count();
        $Page = new Page($count,10);
        $show = $Page->show();
        $this->assign('page',$show);
        return $this->fetch();
    }


//    /**
//     * 搜索用户名
//     */
//    public function search_user()
//    {
//        $search_key = trim(I('search_key'));
//        if ($search_key == '') $this->ajaxReturn(['status'=>-1,'msg'=>'请按要求输入！！']);
//        $list = M('users')->where(['nickname'=>['like',"%$search_key%"]])->select();
//        if ($list){
//            $this->ajaxReturn(['status'=>1,'msg'=>'获取成功','result'=>$list]);
//        }
//        $this->ajaxReturn(['status'=>-1,'msg'=>'未查询到相应数据！！']);
//    }

    /**
     * 分销树状关系
     */
    public function ajax_distribut_tree()
    {
        $list = M('users')->where("first_leader = 1")->select();
        return $this->fetch();
    }

    /**
     *
     * @time 2016/08/31
     * @author dyr
     * 发送站内信
     */
    public function sendMessage()
    {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $users = M('users')->field('user_id,nickname')->where(array('user_id' => array('IN', $user_id_array)))->select();
        }
        $this->assign('users', $users);
        return $this->fetch();
    }

    /**
     * 发送系统消息
     * @author dyr
     * @time  2016/09/01
     */
    public function doSendMessage()
    {
        $call_back = I('call_back');//回调方法
        $text= I('post.text');//内容
        $type = I('post.type', 0);//个体or全体
        $admin_id = session('admin_id');
        $users = I('post.user/a');//个体id
        $message = array(
            'admin_id' => $admin_id,
            'message' => $text,
            'category' => 0,
            'send_time' => time()
        );

        if ($type == 1) {
            //全体用户系统消息
            $message['type'] = 1;
            M('Message')->add($message);
        } else {
            //个体消息
            $message['type'] = 0;
            if (!empty($users)) {
                $create_message_id = M('Message')->add($message);
                foreach ($users as $key) {
                    M('user_message')->add(array('user_id' => $key, 'message_id' => $create_message_id, 'status' => 0, 'category' => 0));
                }
            }
        }
        echo "<script>parent.{$call_back}(1);</script>";
        exit();
    }

    /**
     *
     * @time 2016/09/03
     * @author dyr
     * 发送邮件
     */
    public function sendMail()
    {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $user_where = array(
                'user_id' => array('IN', $user_id_array),
                'email' => array('neq', '')
            );
            $users = M('users')->field('user_id,nickname,email')->where($user_where)->select();
        }
        $this->assign('smtp', tpCache('smtp'));
        $this->assign('users', $users);
        return $this->fetch();
    }

    /**
     * 发送邮箱
     * @author dyr
     * @time  2016/09/03
     */
    public function doSendMail()
    {
        $call_back = I('call_back');//回调方法
        $message = I('post.text');//内容
        $title = I('post.title');//标题
        $users = I('post.user/a');
        $email= I('post.email');
        if (!empty($users)) {
            $user_id_array = implode(',', $users);
            $users = M('users')->field('email')->where(array('user_id' => array('IN', $user_id_array)))->select();
            $to = array();
            foreach ($users as $user) {
                if (check_email($user['email'])) {
                    $to[] = $user['email'];
                }
            }
            $res = send_email($to, $title, $message);
            echo "<script>parent.{$call_back}({$res['status']});</script>";
            exit();
        }
        if($email){
            $res = send_email($email, $title, $message);
            echo "<script>parent.{$call_back}({$res['status']});</script>";
            exit();
        }
    }
    /**
     *  转账汇款记录
     */
    public function remittance(){
        $status = I('status',1);
        $realname = I('realname');
        $bank_card = I('bank_card');
        $where['status'] = $status;
        $realname && $where['realname'] = array('like','%'.$realname.'%');
        $bank_card && $where['bank_card'] = array('like','%'.$bank_card.'%');

        $create_time = urldecode(I('create_time'));
        // echo urldecode($create_time);
        // echo $create_time;exit;
        // $create_time = str_replace('+', '', $create_time);

        $create_time = $create_time  ? $create_time  : date('Y-m-d H:i:s',strtotime('-1 year')).','.date('Y-m-d H:i:s',strtotime('+1 day'));
        $create_time3 = explode(',',$create_time);
        $this->assign('start_time',$create_time3[0]);
        $this->assign('end_time',$create_time3[1]);
        if($status == 2){
            $time_name = 'pay_time';
            $export_time_name = '转账时间';
            $export_status = '已转账';
        }else{
            $time_name = 'check_time';
            $export_time_name = '审核时间';
            $export_status = '待转账';
        }
        $where[$time_name] =  array(array('gt', strtotime($create_time3[0])), array('lt', strtotime($create_time3[1])));
        $withdrawalsModel = new Withdrawals();
        $count = $withdrawalsModel->where($where)->count();
        $Page = new page($count,C('PAGESIZE'));
        $list = $withdrawalsModel->where($where)->limit($Page->firstRow,$Page->listRows)->order("id desc")->select();
        if (I('export') == 1) {
            # code...导出记录
            $selected = I('selected');
            if (!empty($selected)) {
                $selected_arr = explode(',', $selected);
                $where['id'] = array('in',$selected_arr);
            }
            $list = $withdrawalsModel->where($where)->order("id desc")->select();
            $strTable ='<table width="500" border="1">';
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">用户昵称</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="100">银行机构名称</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">账户号码</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">账户开户名</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">申请金额</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">状态</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">'.$export_time_name.'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">备注</td>';
            $strTable .= '</tr>';
            if(is_array($list)){
                foreach($list as $k=>$val){
                    $strTable .= '<tr>';
                    $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['users']['nickname'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['bank_name'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['bank_card'].'</td>';
                    $strTable .= '<td style="vnd.ms-excel.numberformat:@">'.$val['realname'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['money'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$export_status.'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i:s',$val[$time_name]).'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['remark'].'</td>';
                    $strTable .= '</tr>';
                }
            }
            $strTable .='</table>';
            unset($remittanceList);
            downloadExcel($strTable,'remittance');
            exit();
        }

        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('status',$status);
        $this->assign('Page',$Page);
        $this->assign('list',$list);
        return $this->fetch();
    }

    /**
     * 提现申请记录
     */
    public function withdrawals()
    {
        $this->get_withdrawals_list();
        $this->assign('withdraw_status',C('WITHDRAW_STATUS'));
        return $this->fetch();
    }

    public function get_withdrawals_list($status=''){
        $id = I('selected/a');
        $user_id = I('user_id/d');
        $realname = I('realname');
        $bank_card = I('bank_card');
        $create_time = urldecode(I('create_time'));
        $create_time = $create_time  ? $create_time  : date('Y-m-d H:i:s',strtotime('-1 year')).','.date('Y-m-d H:i:s',strtotime('+1 day'));
        $create_time3 = explode(',',$create_time);
        $this->assign('start_time',$create_time3[0]);
        $this->assign('end_time',$create_time3[1]);
        $where['w.create_time'] =  array(array('gt', strtotime($create_time3[0])), array('lt', strtotime($create_time3[1])));

        $status = empty($status) ? I('status') : $status;
        if($status !== ''){
            $where['w.status'] = $status;
        }else{
            $where['w.status'] = ['lt',2];
        }
        if($id){
            $where['w.id'] = ['in',$id];
        }
        $user_id && $where['u.user_id'] = $user_id;
        $realname && $where['w.realname'] = array('like','%'.$realname.'%');
        $bank_card && $where['w.bank_card'] = array('like','%'.$bank_card.'%');
        $export = I('export');
        if($export == 1){
            $strTable ='<table width="500" border="1">';
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">申请人</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="100">提现金额</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">银行名称</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">银行账号</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">开户人姓名</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">申请时间</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">提现备注</td>';
            $strTable .= '</tr>';
            $remittanceList = Db::name('withdrawals')->alias('w')->field('w.*,u.nickname')->join('__USERS__ u', 'u.user_id = w.user_id', 'INNER')->where($where)->order("w.id desc")->select();
            if(is_array($remittanceList)){
                foreach($remittanceList as $k=>$val){
                    $strTable .= '<tr>';
                    $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['nickname'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['money'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['bank_name'].'</td>';
                    $strTable .= '<td style="vnd.ms-excel.numberformat:@">'.$val['bank_card'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['realname'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i:s',$val['create_time']).'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['remark'].'</td>';
                    $strTable .= '</tr>';
                }
            }
            $strTable .='</table>';
            unset($remittanceList);
            downloadExcel($strTable,'remittance');
            exit();
        }
        $count = Db::name('withdrawals')->alias('w')->join('__USERS__ u', 'u.user_id = w.user_id', 'INNER')->where($where)->count();
        $Page  = new Page($count,20);
        $list = Db::name('withdrawals')->alias('w')->field('w.*,u.nickname')->join('__USERS__ u', 'u.user_id = w.user_id', 'INNER')->where($where)->order("w.id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        //$this->assign('create_time',$create_time2);
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('list',$list);
        $this->assign('pager',$Page);
        C('TOKEN_ON',false);
    }

    /**
     * 删除申请记录
     */
    public function delWithdrawals()
    {
        $id = I('del_id/d');
        $res = Db::name("withdrawals")->where(['id'=>$id])->delete();
        if($res !== false){
            $return_arr = ['status' => 1,'msg' => '操作成功','data'  =>'',];
        }else{
            $return_arr = ['status' => -1,'msg' => '删除失败','data'  =>'',];
        }
        $this->ajaxReturn($return_arr);
    }

    /**
     * 修改编辑 申请提现
     */
    public  function editWithdrawals(){
        $id = I('id');
        $withdrawals = Db::name("withdrawals")->find($id);
        $user = M('users')->where(['user_id' => $withdrawals['user_id']])->find();
        if($user['nickname'])
            $withdrawals['user_name'] = $user['nickname'];
        elseif($user['email'])
            $withdrawals['user_name'] = $user['email'];
        elseif($user['mobile'])
            $withdrawals['user_name'] = $user['mobile'];
        $status = $withdrawals['status'];
        $withdrawals['status_code'] = C('WITHDRAW_STATUS')["$status"];
        $this->assign('user',$user);
        $this->assign('data',$withdrawals);
        return $this->fetch();
    }

    /**
     *  处理会员提现申请
     */
    public function withdrawals_update(){
        $id_arr = I('id/a');
        $data['status']=$status = I('status');
        $data['remark'] = I('remark');
        if($status == 1) $data['check_time'] = time();
        if($status != 1) $data['refuse_time'] = time();
        $ids = implode(',',$id_arr);
        $r = Db::name('withdrawals')->whereIn('id',$ids)->update($data);
        if($r !== false){
            $this->ajaxReturn(array('status'=>1,'msg'=>"操作成功"),'JSON');
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>"操作失败"),'JSON');
        }
    }
    // 用户申请提现
    public function transfer(){
        $id = I('selected/a');
        if(empty($id))$this->error('请至少选择一条记录');
        $atype = I('atype');
        if(is_array($id)){
            $withdrawals = M('withdrawals')->where('id in ('.implode(',', $id).')')->select();
        }else{
            $withdrawals = M('withdrawals')->where(array('id'=>$id))->select();
        }
        $alipay['batch_num'] = 0;
        $alipay['batch_fee'] = 0;
        foreach($withdrawals as $val){
            $user = M('users')->where(array('user_id'=>$val['user_id']))->find();
            $oauthUsers = M("OauthUsers")->where(['user_id'=>$user['user_id'] , 'oauth_child'=>'mp'])->find();
            //获取用户绑定openId
            $user['openid'] = $oauthUsers['openid'];
            if($user['user_money'] < $val['money'])
            {
                $data = array('status'=>-2,'remark'=>'账户余额不足');
                M('withdrawals')->where(array('id'=>$val['id']))->save($data);
                $this->error('账户余额不足');
            }else{
                $rdata = array('type'=>1,'money'=>$val['money'],'log_type_id'=>$val['id'],'user_id'=>$val['user_id']);
                if($atype == 'online'){
                    header("Content-type: text/html; charset=utf-8");
                    exit("请联系st官网客服购买高级版支持此功能");
                }else{
                    accountLog($val['user_id'], ($val['money'] * -1), 0,"管理员处理用户提现申请");//手动转账，默认视为已通过线下转方式处理了该笔提现申请
                    $r = M('withdrawals')->where(array('id'=>$val['id']))->save(array('status'=>2,'pay_time'=>time()));
                    expenseLog($rdata);//支出记录日志

                }
            }
        }
        if($alipay['batch_num']>0){
            //支付宝在线批量付款
            include_once  PLUGIN_PATH."payment/alipay/alipay.class.php";
            $alipay_obj = new \alipay();
            $alipay_obj->transfer($alipay);
        }
        $this->success("操作成功!",U('remittance'),3);
    }

    public function rebate_log(){
        $parentid = session('user_id');
        $condition = array();
        if($parentid){
            $condition['parent_id'] = $parentid;
        }
        //获取类型
        $type = I('get.type');
        //获取记录总数
        $count = M('account_log')->where($condition)->count();
        $page = new Page($count);
        $lists  = M('account_log')->where($condition)->order('change_time desc')->limit($page->firstRow.','.$page->listRows)->select();
        foreach ($lists as $list=>&$item) {
            $item['users'] = Db::name('users')->find($item['user_id']);
        }
        $this->assign('page',$page->show());
        $this->assign('lists',$lists);
        return $this->fetch();
    }
    public function tixian(){
        $parentid = session('user_id');
        $this->assign('parentid',$parentid);
        return $this->fetch();
    }
    public function ajaxtxindex(){
        $stateArr = array('0'=>'审核中','1'=>'已提现','2'=>'拒绝');
        $condition = array();
        $nickname = I('nickname');
        $account = I('account');
        $account ? $condition['email|mobile'] = ['like',"%$account%"] : false;
        $nickname ? $condition['nickname'] = ['like',"%$nickname%"] : false;
        $condition['distribut_level'] = ['lt',"3"];
        $sort_order = I('order_by').' '.I('sort');

        $usersModel = new Users();
        $userIdArr= $usersModel->where($condition)->column('user_id');

        $userIds= implode(",",$userIdArr);
        $conditiont['uid'] = ['in',$userIds];
        $count = Db::name('user_txrecord')->where($conditiont)->count();
        $Page  = new AjaxPage($count,10);
        $txList = Db::name('user_txrecord')->where($conditiont)->order($sort_order)->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach ($txList as $key=>&$item) {
            $item['statename'] = $stateArr[$item['type']];
        }
        $show = $Page->show();
        $this->assign('txList',$txList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }
    public function export_tixian(){
        $stateArr = array('0'=>'审核中','1'=>'已提现','2'=>'拒绝');
        $strTable ='<table width="700" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">会员ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">会员昵称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">提现金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">提现时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">提现状态</td>';
        $strTable .= '</tr>';
        $user_ids =I('user_ids');
        $condition['distribut_level'] = array("lt",'3');
        if($user_ids){
            $condition['user_id']=['in',$user_ids];
        }else{
            $mobile =I('mobile');
            $email =I('email');
            $mobile ? $condition['mobile'] = $mobile : false;
            $email ? $condition['email'] = $email : false;
        };
        $uidArr = DB::name('users')->where($condition)->column('user_id');
        $uids = implode(',',$uidArr);

        $conditiont['uid']=['in',$uids];
        $count = DB::name('user_txrecord')->where($conditiont)->count();
        $p = ceil($count/5000);
        for($i=0;$i<$p;$i++){
            $start = $i*5000;
            $end = ($i+1)*5000;
            $userList = M('user_txrecord')->where($conditiont)->order('uid')->limit($start.','.$end)->select();

            if(is_array($userList)){
                foreach($userList as $k=>$val){
                    $val['distribut_level']==2?$val['distribut_name']='城市合伙人':$val['distribut_name']='省级合伙人';
                    $strTable .= '<tr>';
                    $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['uid'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['nickname'].' </td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['money'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['add_time'].'</td>';
                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$stateArr[$val['type']].'</td>';
                    $strTable .= '</tr>';
                }
                unset($userList);
            }
        }
        $strTable .='</table>';
        downloadExcel($strTable,'users_'.$i);
        exit();
    }
    public function changeState(){
        $id = I('id');

        $state = I('state');
        $condition['id'] = $id;
        $condition['type'] = $state;
        $info = Db::name('user_txrecord')->find($id);
        $res =  Db::name('user_txrecord')->update($condition);
        $stateArr = array('0'=>'审核中','1'=>'已提现','2'=>'拒绝');
        if($state==1){
            accountLog($info['uid'],-$info['money'],0,'提现'.$info['money'],0);
        }
        if($res){
            $this->ajaxReturn(array('status' => 1, 'msg' => '更新成功', 'data' => $stateArr[$state]));
        }

    }

    /**
     * 签到列表
     * @date 2017/09/28
     */
    public function signList() {
        header("Content-type: text/html; charset=utf-8");
        exit("请联系st官网客服购买高级版支持此功能");
    }


    /**
     * 会员签到 ajax
     * @date 2017/09/28
     */
    public function ajaxsignList() {
        header("Content-type: text/html; charset=utf-8");
        exit("请联系st官网客服购买高级版支持此功能");
    }

    /**
     * 签到规则设置
     * @date 2017/09/28
     */
    public function signRule() {
        header("Content-type: text/html; charset=utf-8");
        exit("请联系st官网客服购买高级版支持此功能");
    }
}